import xml.etree.ElementTree as ET
import os
import cv2
import numpy as np
import shutil
import random

def getannotion(xmlPath):

    tree = ET.parse(xmlPath)
    root = tree.getroot()
    bboxes = []
    labels = []
    for obj in root.findall('object'):
        label = obj.find('name').text
        bnd_box = obj.find('bndbox')
        bbox = [
            int(bnd_box.find('xmin').text),
            int(bnd_box.find('ymin').text),
            int(bnd_box.find('xmax').text),
            int(bnd_box.find('ymax').text)]
        bboxes.append(bbox)
        labels.append(label)

    bboxes = np.array(bboxes, ndmin=2).astype(np.float32)
    # labels = np.array(labels)

    return bboxes, labels


def getxmlinfo(xmlpath):
    tree = ET.parse(xmlpath)
    root = tree.getroot()
    filename = root.find('filename').text
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)
    return filename, w, h



def indent(elem, level=0):
    i = "\n" + level*"\t"
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "\t"
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

def generateXML(outPath,filename,w,h,bboxes,labels):

    root = ET.Element('annotation')
    xfolder = ET.SubElement(root,'folder')
    xfolder.text = 'images'
    xfilename = ET.SubElement(root,'filename')
    xfilename.text = filename
    xpath = ET.SubElement(root,'path')
    xpath.text = 'images/'+filename
    xsource = ET.SubElement(root,'source')
    xdatabase = ET.SubElement(xsource,'database')
    xdatabase.text = 'Unknown'

    xsize = ET.SubElement(root,'size')
    xwidth = ET.SubElement(xsize,'width')
    xwidth.text = str(w)
    xheight = ET.SubElement(xsize,'height')
    xheight.text = str(h)
    depth = ET.SubElement(xsize,'depth')
    depth.text = '3'

    xsegmented = ET.SubElement(root,'segmented')
    xsegmented.text = '0'

    for i in range(len(bboxes)):
        xxobject = ET.SubElement(root,'object')
        xxname = ET.SubElement(xxobject,'name')
        xxname.text = labels[i]
        xxpose = ET.SubElement(xxobject,'pose')
        xxpose.text = 'Unspecified'
        xxdifficult = ET.SubElement(xxobject,'difficult')
        xxdifficult.text = '0'
        xxtruncated = ET.SubElement(xxobject,'truncated')
        xxtruncated.text = '0'
        xxbndbox = ET.SubElement(xxobject,'bndbox')
        xxmin = ET.SubElement(xxbndbox,'xmin')
        xxmin.text = str(int(bboxes[i][0]))
        xymin = ET.SubElement(xxbndbox,'ymin')
        xymin.text = str(int(bboxes[i][1]))
        xxmax = ET.SubElement(xxbndbox,'xmax')
        xxmax.text = str(int(bboxes[i][2]))
        xymax = ET.SubElement(xxbndbox,'ymax')
        xymax.text = str(int(bboxes[i][3]))

    tree = ET.ElementTree(root)
    indent(root)

    tree.write(outPath,encoding='utf-8')


# def Resize_img_xml(srcpath,outpath,scale_rate=0.25):
#     for imgfile in os.listdir(srcpath):
#
#         file_name = os.path.splitext(imgfile)[0]
#         file_post = os.path.splitext(imgfile)[1].lower()
#         xml_name = file_name + '.xml'
#
#         if file_post == '.jpg' or file_post == '.png' or file_post == '.jpeg':
#             img = cv2.imread(os.path.join(srcpath, imgfile))
#             bboxes , labels = getannotion(os.path.join(srcpath, xml_name))
#             img_resize = cv2.resize(img, None,fx=scale_rate,fy=scale_rate)
#             bboxes[:, :4] *=(scale_rate)
#             cv2.imwrite(outpath+"/"+imgfile,img_resize)
#             generateXML(outpath+"/"+xml_name,imgfile,img_resize.shape[1], img_resize.shape[0],bboxes,labels)


def Resize_img_xml(srcpath,outpath,max_length=1600):
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    for imgfile in os.listdir(srcpath):

        file_name = os.path.splitext(imgfile)[0]
        file_post = os.path.splitext(imgfile)[1].lower()
        xml_name = file_name + '.xml'

        if file_post == '.jpg' or file_post == '.png' or file_post == '.jpeg':
            if not  os.path.exists(os.path.join(outpath,imgfile)):
                img = cv2.imread(os.path.join(srcpath, imgfile))
                bboxes , labels = getannotion(os.path.join(srcpath, xml_name))
                scale_rate = get_resize_rate(img.shape[1],img.shape[0],max_length)
                if scale_rate<1.0:
                    img_resize = cv2.resize(img, None,fx=scale_rate,fy=scale_rate)
                    bboxes[:, :4] *=(scale_rate)
                    cv2.imwrite(outpath+"/"+imgfile,img_resize)
                    generateXML(outpath+"/"+xml_name,imgfile,img_resize.shape[1], img_resize.shape[0],bboxes,labels)
                else:
                    shutil.copy(os.path.join(srcpath,imgfile),os.path.join(outpath,imgfile))
                    shutil.copy(os.path.join(srcpath,xml_name),os.path.join(outpath,xml_name))

def Resize_img(srcpath,outpath,max_length=1600):
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    for imgfile in os.listdir(srcpath):

        file_name = os.path.splitext(imgfile)[0]
        file_post = os.path.splitext(imgfile)[1].lower()
        # xml_name = file_name + '.xml'

        if file_post == '.jpg' or file_post == '.png' or file_post == '.jpeg':
            if not  os.path.exists(os.path.join(outpath,imgfile)):
                img = cv2.imread(os.path.join(srcpath, imgfile))
                # bboxes , labels = getannotion(os.path.join(srcpath, xml_name))
                scale_rate = get_resize_rate(img.shape[1],img.shape[0],max_length)
                if scale_rate<1.0:
                    img_resize = cv2.resize(img, None,fx=scale_rate,fy=scale_rate)
                    # bboxes[:, :4] *=(scale_rate)
                    cv2.imwrite(outpath+"/"+imgfile,img_resize)
                    # generateXML(outpath+"/"+xml_name,imgfile,img_resize.shape[1], img_resize.shape[0],bboxes,labels)
                else:
                    shutil.copy(os.path.join(srcpath,imgfile),os.path.join(outpath,imgfile))
                    # shutil.copy(os.path.join(srcpath,xml_name),os.path.join(outpath,xml_name))


def get_resize_rate(w,h,max_length):
    max_edge=max(w,h)
    rate = max_length/max_edge
    return rate

def Rotate_L_img_xml(srcpath,outpath):
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    for imgfile in os.listdir(srcpath):

        file_name = os.path.splitext(imgfile)[0]
        file_post = os.path.splitext(imgfile)[1].lower()
        xml_name = file_name + '.xml'
        new_img_name = file_name+'_rotateL90'+file_post
        new_xml_name = file_name+'_rotateL90'+'.xml'


        if file_post == '.jpg' or file_post == '.png' or file_post == '.jpeg':
            img = cv2.imread(os.path.join(srcpath, imgfile))
            bboxes , labels = getannotion(os.path.join(srcpath, xml_name))
            print(bboxes[0],labels[0])
            w = img.shape[1]
            h = img.shape[0]
            for box in bboxes:
                xmin = box[0]
                ymin = box[1]
                xmax = box[2]
                ymax = box[3]

                box[0] = ymin
                box[1] = w-xmax
                box[2] = ymax
                box[3] = w-xmin


            rotateimg = cv2.rotate(img,rotateCode=cv2.ROTATE_90_COUNTERCLOCKWISE)
            cv2.imwrite(os.path.join(outpath, new_img_name), rotateimg)
            generateXML(os.path.join(outpath, new_xml_name), new_img_name, rotateimg.shape[1], rotateimg.shape[0], bboxes, labels)


def remove_sku(path,skulist):
    for xmlfile in os.listdir(path):
        if xmlfile.endswith('.xml'):
            to_del=[]
            bboxes, labels = getannotion(os.path.join(path, xmlfile))
            for i in range(len(labels)):
                if labels[i] in skulist:
                    to_del.append(i)

            if len(to_del)>0:
                print(xmlfile)
                nbboxes = np.delete(bboxes,to_del,0)
                nlabels = np.delete(labels,to_del,0)
                filename,w,h =getxmlinfo(os.path.join(path, xmlfile))
                generateXML(os.path.join(path, xmlfile), filename, w, h, nbboxes,nlabels)


def remove_one_sku(path,skulist):
    for xmlfile in os.listdir(path):
        if xmlfile.endswith('.xml'):
            to_del=[]
            bboxes, labels = getannotion(os.path.join(path, xmlfile))
            for i in range(len(labels)):
                if labels[i] in skulist:
                    if bboxes[i][1]<20:
                        to_del.append(i)

            if len(to_del)>0:
                print(xmlfile)
                nbboxes = np.delete(bboxes,to_del,0)
                nlabels = np.delete(labels,to_del,0)
                filename,w,h =getxmlinfo(os.path.join(path, xmlfile))
                generateXML(os.path.join(path, xmlfile), filename, w, h, nbboxes,nlabels)


def keep_sku(path,skulist):
    for xmlfile in os.listdir(path):
        if xmlfile.endswith('.xml'):
            to_del=[]
            bboxes, labels = getannotion(os.path.join(path, xmlfile))
            for i in range(len(labels)):
                if not labels[i] in skulist:
                    to_del.append(i)

            if len(to_del)>0:
                print(xmlfile)
                nbboxes = np.delete(bboxes,to_del,0)
                nlabels = np.delete(labels,to_del,0)
                filename,w,h =getxmlinfo(os.path.join(path, xmlfile))
                generateXML(os.path.join(path, xmlfile), filename, w, h, nbboxes,nlabels)

def copyXml(path):
    for subdir in os.listdir(path):
        allfiles = os.listdir(os.path.join(path,subdir))
        for files in allfiles:
            if files.endswith('.xml'):
                bboxes, labels = getannotion(os.path.join(path, subdir, files))
                filename, w, h = getxmlinfo(os.path.join(path, subdir, files))

        for imgfile in allfiles:
            if not os.path.splitext(imgfile)[0] == os.path.splitext(filename)[0]:
                newxmlfile = os.path.splitext(imgfile)[0] + '.xml'
                generateXML(os.path.join(path, subdir, newxmlfile), imgfile, w, h, bboxes, labels)

def getXml(path,outpath):
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    for subdir in os.listdir(path):
        allfiles = os.listdir(os.path.join(path,subdir))
        for files in allfiles:
            if files.endswith('.xml'):
                shutil.copy(os.path.join(path,subdir,files),os.path.join(outpath,files))


def movePic_Xml(path,outpath):
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    for subdir in os.listdir(path):
        for files in os.listdir(os.path.join(path,subdir)):
            # print(os.path.join(path,subdir,files))
            print(files)
            shutil.move(os.path.join(path,subdir,files),os.path.join(outpath,files))


def rename_pic_xml(srcpath,outpath):
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    index = 1
    for imgfile in os.listdir(srcpath):

        file_name = os.path.splitext(imgfile)[0]
        file_post = os.path.splitext(imgfile)[1].lower()
        xml_name = file_name + '.xml'
        # new_img_name = file_name+'_mixup6'+file_post
        # new_xml_name = file_name+'_mixup6'+'.xml'
        new_img_name = 'whh_sku_20200619_'+str(index)+file_post
        new_xml_name = 'whh_sku_20200619_'+str(index)+'.xml'
        index+=1


        if file_post == '.jpg' or file_post == '.png' or file_post == '.jpeg':
            img = cv2.imread(os.path.join(srcpath, imgfile))
            bboxes , labels = getannotion(os.path.join(srcpath, xml_name))
            w = img.shape[1]
            h = img.shape[0]
            
            cv2.imwrite(os.path.join(outpath, new_img_name), img)
            generateXML(os.path.join(outpath, new_xml_name), new_img_name, w, h, bboxes, labels)

def data_to_txt(srcpath,outpath,trainortest):
    Annotations_dir = os.path.join(outpath,'Annotations')
    JPEGImages_dir = os.path.join(outpath,'JPEGImages')
    ImageSets_dir = os.path.join(outpath,'ImageSets','Main')
    if not os.path.exists(Annotations_dir):
        os.makedirs(Annotations_dir)
    if not os.path.exists(JPEGImages_dir):
        os.makedirs(JPEGImages_dir)
    if not os.path.exists(ImageSets_dir):
        os.makedirs(ImageSets_dir)

    filelist = os.listdir(srcpath)
    listText = open(ImageSets_dir + '/' + trainortest+'.txt', 'w')
    for file in filelist:
        filename = os.path.splitext(file)[0]
        filepost = os.path.splitext(file)[1]
        # if filepost.lower() in ['.jpg','.png','.jpeg']:
        if filepost.lower() == '.jpg':
            name = str(os.path.splitext(file)[0])+ '\n'
            listText.write(name)
            shutil.copy(os.path.join(srcpath,file),os.path.join(JPEGImages_dir,file))
        elif filepost.lower() == '.xml':
            shutil.copy(os.path.join(srcpath,file),os.path.join(Annotations_dir,file))
            pass
    listText.close()

def compare_gt_bottle(gtpath,bottlepath,outputpath):
    for gtxml in os.listdir(gtpath):
        file_name = os.path.splitext(gtxml)[0]
        file_post = os.path.splitext(gtxml)[1].lower()
        if file_post == '.xml':
            if os.path.exists(os.path.join(bottlepath,gtxml)):
                print(gtxml)
                bboxes_gt, labels_gt = getannotion(os.path.join(gtpath, gtxml))
                bboxes_bottle, labels_bottle = getannotion(os.path.join(bottlepath, gtxml))

                for i in range(len(bboxes_bottle)):
                    for j in range(len(bboxes_gt)):
                        area_gt = get_area(bboxes_gt[j])
                        area_bottle = get_area(bboxes_bottle[i])
                        area_iou = iou_area(bboxes_gt[j],bboxes_bottle[i])
                        iou = area_iou / max(area_gt, area_bottle)
                        if iou > 0.7 :
                            print(labels_gt[j],labels_bottle[i])
                            labels_bottle[i] = labels_gt[j]
                            print(labels_bottle[i])
                filename, w, h = getxmlinfo(os.path.join(gtpath, gtxml))
                generateXML(os.path.join(outputpath, gtxml), filename, w, h, bboxes_bottle, labels_bottle)


def compare_del_gt_bottle(gtpath,bottlepath,outputpath):
    for gtxml in os.listdir(gtpath):
        file_name = os.path.splitext(gtxml)[0]
        file_post = os.path.splitext(gtxml)[1].lower()
        if file_post == '.xml':
            if os.path.exists(os.path.join(bottlepath,gtxml)):
                print(gtxml)
                bboxes_gt, labels_gt = getannotion(os.path.join(gtpath, gtxml))
                bboxes_bottle, labels_bottle = getannotion(os.path.join(bottlepath, gtxml))
                to_del = []
                for i in range(len(bboxes_bottle)):
                    for j in range(len(bboxes_gt)):
                        area_gt = get_area(bboxes_gt[j])
                        area_bottle = get_area(bboxes_bottle[i])
                        area_iou = iou_area(bboxes_gt[j],bboxes_bottle[i])
                        iou = area_iou / max(area_gt, area_bottle)
                        if iou > 0.7 :
                            print(labels_gt[j],labels_bottle[i])
                            # labels_bottle[i] = labels_gt[j]
                            to_del.append(i)
                            print(labels_bottle[i])
                # to_del.reverse()
                if len(to_del)>0:
                    for k in to_del:
                        nlabels_bottle = np.delete(labels_bottle, to_del, 0)
                        nbboxes_bottle = np.delete(bboxes_bottle, to_del, 0)
                filename, w, h = getxmlinfo(os.path.join(gtpath, gtxml))
                generateXML(os.path.join(outputpath, gtxml), filename, w, h, nbboxes_bottle, nlabels_bottle)


def compare_del_bottle(gtpath,bottlepath,outputpath,label=None):
    if not os.path.exists(outputpath):
        os.makedirs(outputpath)
    tbar = os.listdir(gtpath)
    for gtxml in tbar:
        file_name = os.path.splitext(gtxml)[0]
        file_post = os.path.splitext(gtxml)[1].lower()
        if file_post == '.xml':
            tbar.desc = gtxml
            if os.path.exists(os.path.join(bottlepath,gtxml)):
                bboxes_gt, labels_gt = getannotion(os.path.join(gtpath, gtxml))
                bboxes_bottle, labels_bottle = getannotion(os.path.join(bottlepath, gtxml))
                to_del = []
                for i in range(len(bboxes_bottle)):
                    numGt = len(bboxes_gt)
                    if len(bboxes_bottle[i]) == 0:
                        print(gtxml, bboxes_bottle[i], ("has no predict bboxes."))
                        continue
                    for j in range(numGt):
                        if len(bboxes_gt[j]) == 0:
                            print(gtxml, bboxes_gt[j], ("has no gt bboxes."))
                            continue
                        area_gt = get_area(bboxes_gt[j])
                        area_bottle = get_area(bboxes_bottle[i])
                        area_iou = iou_area(bboxes_gt[j],bboxes_bottle[i])
                        iou = area_iou / max(area_gt, area_bottle)
                        if iou >= 0.4 :
                            # print(labels_gt[j],labels_bottle[i])
                            # labels_bottle[i] = labels_gt[j]
                            to_del.append(i)
                            # print(labels_bottle[i])
                # to_del.reverse()
                if len(to_del) > 0:
                    for k in to_del:
                        nlabels_bottle = np.delete(labels_bottle, to_del, 0)
                        nbboxes_bottle = np.delete(bboxes_bottle, to_del, 0)
                else:
                    nlabels_bottle = labels_bottle
                    nbboxes_bottle = bboxes_bottle
                try:
                    if len(labels_bottle) > 0 and len(labels_gt) > 0:
                        nlabels_bottle = np.concatenate((nlabels_bottle, labels_gt))
                        nbboxes_bottle = np.concatenate((nbboxes_bottle, bboxes_gt))
                    elif len(labels_bottle) > 0 and len(labels_gt) == 0:
                        nlabels_bottle = np.array(labels_bottle)
                        nbboxes_bottle = np.array(bboxes_bottle)
                    elif len(labels_bottle) == 0 and len(labels_gt) > 0:
                        nlabels_bottle = np.array(labels_gt)
                        nbboxes_bottle = np.array(bboxes_gt)
                    else:
                        print("?????????")
                except:
                    print("[error] some predict bbox and gt bbox shape don't match, maybe.")
                if label is not None:
                    nlabels_bottle[:] = label
                filename, w, h = getxmlinfo(os.path.join(gtpath, gtxml))
                # os.system("cp -r \"%s\" \"%s\"" % (os.path.join(gtpath, filename), os.path.join(outputpath, filename)))
                generateXML(os.path.join(outputpath, gtxml), filename, w, h, nbboxes_bottle, nlabels_bottle)

def get_area(box):
    return (box[2]-box[0])*(box[3]-box[1])

def iou_area(list1, list2):
    xmin = max(list1[0], list2[0])
    xmax = min(list1[2], list2[2])
    ymin = max(list1[1], list2[1])
    ymax = min(list1[3], list2[3])
    if xmin >= xmax or ymin >= ymax:
        return 0
    else:
        return (xmax - xmin) * (ymax - ymin)


def splite_data(path):
    traindir = os.path.join(path,"train")
    testdir = os.path.join(path,"test")
    if not os.path.exists(traindir):
        os.mkdir(traindir)
    if not os.path.exists(testdir):
        os.mkdir(testdir)

    datalist = os.listdir(path)
    print(datalist)
    random.shuffle(datalist)
    print(datalist)
    nums = len(datalist)
    index = 0
    for file in datalist:
        prefilename = os.path.splitext(file)[0]
        postfilename = os.path.splitext(file)[1]
        if postfilename.lower() == ".jpg" or postfilename.lower() == ".jpeg" or postfilename.lower() == ".png":
            if os.path.exists(os.path.join(path,prefilename+".xml")):

                print(file)
                index += 1
                if index < (nums-2)*0.45:
                    shutil.move(os.path.join(path,file),os.path.join(traindir,file))
                    shutil.move(os.path.join(path,prefilename+".xml"),os.path.join(traindir,prefilename+".xml"))
                else:
                    shutil.move(os.path.join(path, file), os.path.join(testdir, file))
                    shutil.move(os.path.join(path, prefilename + ".xml"), os.path.join(testdir, prefilename + ".xml"))

            else:
                os.remove(os.path.join(path,file))


def del_pic_no_xml(path):
    json_files = os.listdir(path)

    for file in json_files:
        prefilename = os.path.splitext(file)[0]
        postfilename = os.path.splitext(file)[1]
        if postfilename.lower() == ".jpg" or postfilename.lower() == ".jpeg" or postfilename.lower() == ".png":
            if not os.path.exists(os.path.join(path, prefilename + ".xml")):
                print(file)
                os.remove(os.path.join(path,file))


# def crop2xml(croppath,imgpath):
#     outputpath = os.path.join(imgpath,'xml_from_autolabel')
#     if not os.path.exists(outputpath):
#         os.makedirs(outputpath)
#
#     infodict = {}
#     # pdb.set_trace()
#     for img in os.listdir(imgpath):
#         file_name = os.path.splitext(img)[0]
#         file_post = os.path.splitext(img)[1].lower()
#         if file_post == '.jpg' or file_post == '.png' or file_post == '.jpeg':
#             imgtemp = cv2.imread(os.path.join(imgpath, img))
#             w = imgtemp.shape[1]
#             h = imgtemp.shape[0]
#             infodict[file_name] = {'filename':img,'label':[],'bboxes':[],'width':w,'height':h}
#
#     for sublabel in os.listdir(croppath):
#         if os.path.isfile(f'{croppath}/{sublabel}'):
#             continue
#         for cropimg in os.listdir(os.path.join(croppath,sublabel)):
#             cropfileinfo =  os.path.splitext(cropimg)[0]
#             info = cropfileinfo.rsplit('-', 1)
#             imgkey = info[0]
#             bbox = info[-1].split('_')
#
#             bbox = [int(k) for k in bbox]
#             bbox[0] = int(bbox[0]*infodict[imgkey]['width']/1000.0)
#             bbox[1] = int(bbox[1]*infodict[imgkey]['height']/1000.0)
#             bbox[2] = int(bbox[2]*infodict[imgkey]['width']/1000.0)
#             bbox[3] = int(bbox[3]*infodict[imgkey]['height']/1000.0)
#
#             infodict[imgkey]['label'].append(sublabel)
#             infodict[imgkey]['bboxes'].append(bbox)
#
#     for key,value in infodict.items():
#         generateXML(os.path.join(outputpath, key+'.xml'), value['filename'], value['width'], value['height'], value['bboxes'], value['label'])

def crop2xml(croppath, imgpath, outputpath):
    #outputpath = os.path.join(imgpath,'../autoxml')
    if not os.path.exists(outputpath):
        os.makedirs(outputpath)

    infodict = {}

    print("[crop2xml] stage 1")
    for img in os.listdir(imgpath):
        file_name = os.path.splitext(img)[0]
        file_post = os.path.splitext(img)[1].lower()
        if file_post == '.jpg' or file_post == '.png' or file_post == '.jpeg' or file_post == '.JPG' or file_post == '.JPEG':
            imgtemp = cv2.imread(os.path.join(imgpath, img))
            w = imgtemp.shape[1]
            h = imgtemp.shape[0]
            infodict[file_name] = {'filename':img,'label':[],'bboxes':[],'width':w,'height':h}
    print("[crop2xml] stage 2")
    for sublabel in os.listdir(croppath):
        for cropimg in os.listdir(os.path.join(croppath,sublabel)):
            try:
                cropfileinfo =  os.path.splitext(cropimg)[0]
                info = cropfileinfo.rsplit('-', 1)
                imgkey = info[0]
                bbox = info[-1].split('_')
                bbox = [int(k) for k in bbox]
                infodict[imgkey]['label'].append(sublabel)
                infodict[imgkey]['bboxes'].append(bbox)
            except:
                print('exception with ', cropimg)
    print("[crop2xml] stage 3")
    for key,value in infodict.items():
        generateXML(os.path.join(outputpath, key+'.xml'), value['filename'], value['width'], value['height'], value['bboxes'], value['label'])


if __name__ == '__main__':
    # G:\super_model_data\AllSKU\yl_opt_20201026\cuts_bench
    croppath = r'F:\Dataset\nfsq\20210708SKU'
    imgpath = r'F:\Dataset\nfsq\20210708PIC'
    respath = r'F:\Dataset\nfsq\20210708XML'
    crop2xml(croppath, imgpath, respath)

    # gtpath = r'F:\remote\50\whh_ysl_tdyh_jsy\train\images\org'
    # bottlepath = r'F:\remote\50\whh_ysl_tdyh_jsy\train\images\auto'
    # outputpath = r'F:\remote\50\whh_ysl_tdyh_jsy\train\images\nms'
    # gtpath = '/mnt/g/超级模型数据/all_yl_cuts/yl_cola_pesi_yb/demo/gt'
    # bottlepath = '/mnt/g/超级模型数据/all_yl_cuts/yl_cola_pesi_yb/demo/autolabel'
    # outputpath = '/mnt/g/超级模型数据/all_yl_cuts/yl_cola_pesi_yb/demo/'
    # compare_del_bottle(gtpath,bottlepath,outputpath)

    # for demo
    # croppath = '/mnt/g/超级模型数据/AllSKU/fk/cuts'
    # imgpath = '/mnt/g/超级模型数据/AllSKU/fk/'
    # crop2xml(croppath,imgpath)
    #
    # gtpath = '/mnt/g/超级模型数据/AllSKU/fk'
    # bottlepath = '/mnt/g/超级模型数据/AllSKU/fk/xml_from_autolabel'
    # outputpath = '/mnt/g/超级模型数据/AllSKU/fk/xml_after_nms'
    # compare_del_bottle(gtpath,bottlepath,outputpath, label="daiding_104")
